<?php

class Controller {

	static $version = '1.0.0';
	protected $db = array();

	protected $isXMLHttpRequest = false;

	public function __construct() {
		$this->isXMLHttpRequest = strtolower($_SERVER['X-Requested-With']) == 'xmlhttprequest';
	}

	protected function loadSqlite($databaseName) {
		if (!isset($this->db[$databaseName])) {
			if (!class_exists('Sqlite'))
				include PATH_LIB . 'Sqlite.class.php';
			$this->db[$databaseName] = new Sqlite($databaseName);
		}
		return $this->db[$databaseName];
	}

	protected function request($key, $default = '') {
		return isset($_REQUEST[$key]) ? $_REQUEST[$key] : $default;
	}

	protected function requestGet($key, $default = '') {
		return isset($_GET[$key]) ? $_GET[$key] : $default;
	}

	protected function requestPost($key, $default = '') {
		return isset($_POST[$key]) ? $_POST[$key] : $default;
	}

	protected function error($msg){
		$data = array('status' => 0,'msg' => $msg,'data' => array());
		if($this->isXMLHttpRequest){
			$this->jsonBack($data);
		} else {
			$this->jsonpBack($data);
		}
	}

	protected function success(){}

	protected function jsonSuccess($msg = '', $data = array(), $status = 1) {
		$this->jsonBack(array(
			'status' => $status,
			'msg' => $msg,
			'data' => $data
		));
	}

	protected function jsonError($msg, $data = array(), $status = 0) {
		$this->jsonBack(array(
			'status' => $status,
			'msg' => $msg,
			'data' => $data
		));
	}

	protected function jsonBack($data) {
		echo json_encode($data);
		exit(0);
	}

	protected function jsonpSuccess($msg = '', $data = array()) {
		$this->jsonpBack(array(
			'status' => 1,
			'msg' => $msg,
			'data' => $data
		));
	}

	protected function jsonpError($msg) {
		$this->jsonpBack(array(
			'status' => 0,
			'msg' => $msg,
			'data' => array()
		));
	}

	protected function jsonpBack($data) {
		//header('Content-Type: text/javascript;charset=utf-8');
		$callback = $this->request('callback', 'jsonpCallback');
		$json =  json_encode($data);
		echo "<script type=\"text/javascript\">\n\twindow.top.{$callback}({$json});\n</script>";
		exit(0);
	}

	protected function httpError($status, $content = '') {
		switch ($status) {
			case 404:
				header('HTTP/1.1 404 not found');
				echo $content, '<em>version:', self::$version, '</em>';
				break;
		}
		exit(0);
	}
}

?>
